$(document).ready(function() {
    // 检查登录状态
    const userId = localStorage.getItem('userId');
    const role = localStorage.getItem('role');
    
    if (!userId || role !== '0') {
        // 清除所有本地存储的数据
        localStorage.clear();
        window.location.href = '../index.html';
        return;
    }

    // 加载购物车
    loadCart();

    // 退出登录
    $('#logout').click(function(e) {
        e.preventDefault();
        // 清除所有本地存储的数据
        localStorage.clear();
        window.location.href = '../index.html';
    });

    // 提交订单按钮点击事件
    $('#checkoutBtn').click(function() {
        submitOrder();
    });

    // 添加订单确认模态框
    $('body').append(`
        <div id="orderConfirmModal" class="modal" style="display: none;">
            <div class="modal-content">
                <h3>确认订单</h3>
                <div class="order-preview">
                    <div class="order-items"></div>
                    <div class="order-total"></div>
                </div>
                <div class="modal-actions">
                    <button class="primary-btn confirm-order-btn">确认提交</button>
                    <button class="secondary-btn cancel-order-btn">取消</button>
                </div>
            </div>
        </div>
    `);

    // 添加模态框相关的样式
    $('<style>').text(`
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .modal-content {
            background: white;
            padding: 25px;
            border-radius: 8px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .modal h3 {
            margin: 0 0 20px 0;
            color: #333;
            font-size: 1.5rem;
            text-align: center;
        }
        
        .order-preview {
            max-height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
        }
        
        .order-items {
            border-top: 1px solid #eee;
        }
        
        .order-item-preview {
            padding: 15px 0;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .item-name-quantity {
            flex: 1;
        }
        
        .item-name {
            font-weight: 500;
            color: #333;
        }
        
        .item-quantity {
            color: #666;
            font-size: 0.9em;
            margin-top: 4px;
        }
        
        .item-subtotal {
            color: #e44d26;
            font-weight: 500;
            margin-left: 20px;
        }
        
        .order-total {
            margin-top: 20px;
            padding-top: 15px;
            border-top: 2px solid #eee;
            text-align: right;
            font-size: 1.2em;
            font-weight: bold;
            color: #e44d26;
        }
        
        .modal-actions {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 25px;
        }
        
        .modal-actions button {
            padding: 10px 25px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .primary-btn {
            background-color: #4CAF50;
            color: white;
        }
        
        .primary-btn:hover {
            background-color: #45a049;
        }
        
        .secondary-btn {
            background-color: #666;
            color: white;
        }
        
        .secondary-btn:hover {
            background-color: #555;
        }
    `).appendTo('head');

    // 绑定模态框按钮事件
    $('.confirm-order-btn').click(function() {
        $('#orderConfirmModal').hide();
        createOrder(localStorage.getItem('userId'));
    });

    $('.cancel-order-btn').click(function() {
        $('#orderConfirmModal').hide();
    });
});

function loadCart() {
    const userId = localStorage.getItem('userId');
    if (!userId) {
        localStorage.clear();
        window.location.href = '../index.html';
        return;
    }
    
    $.ajax({
        url: `/api/cart/list/${userId}`,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const items = response.data;
                const container = $('#cartItems');
                container.empty();
                
                if (items.length === 0) {
                    showEmptyCart(container);
                    return;
                }

                $('.empty-cart').hide();
                
                let total = 0;
                let hasValidItems = false;
                
                // 先显示有效商品
                items.forEach(item => {
                    if (item.valid) {
                        hasValidItems = true;
                        total += item.money;
                        renderValidCartItem(container, item);
                    }
                });

                // 显示无效商品
                const invalidItems = items.filter(item => !item.valid);
                if (invalidItems.length > 0) {
                    container.append('<div class="invalid-items-section"><h3>失效商品</h3></div>');
                    invalidItems.forEach(item => {
                        renderInvalidCartItem(container, item);
                    });
                }
                
                // 更新结算区域
                updateCheckoutSection(total, hasValidItems);
            } else {
                alert(response.message || '加载购物车失败');
                if (response.code === 401) {
                    localStorage.clear();
                    window.location.href = '../index.html';
                }
            }
        },
        error: function() {
            alert('加载购物车失败，请重试');
        }
    });
}

function renderValidCartItem(container, item) {
    container.append(`
        <div class="cart-item">
            <div class="cart-item-info">
                <h3 class="cart-item-name">${item.commodityName}</h3>
                <div class="cart-item-seller">商家: ${item.sellerName || '未知商家'}</div>
                <div class="cart-item-price">¥${item.price.toFixed(2)}</div>
                <div class="cart-quantity-control">
                    <button onclick="updateQuantity(${item.cartId}, ${item.amount - 1})" 
                            ${item.amount <= 1 ? 'disabled' : ''}>-</button>
                    <span>${item.amount}</span>
                    <button onclick="updateQuantity(${item.cartId}, ${item.amount + 1})">+</button>
                </div>
                <div class="cart-item-total">¥${item.money.toFixed(2)}</div>
            </div>
            <div class="cart-item-actions">
                <button class="delete-btn" onclick="removeItem(${item.cartId})">删除</button>
            </div>
        </div>
    `);
}

function renderInvalidCartItem(container, item) {
    container.append(`
        <div class="cart-item invalid">
            <div class="cart-item-info">
                <h3 class="cart-item-name">${item.commodityName}</h3>
                <div class="cart-item-seller">商家: ${item.sellerName || '未知商家'}</div>
                <div class="cart-item-price">¥${item.price.toFixed(2)}</div>
                <div class="invalid-reason">${item.invalidReason}</div>
            </div>
            <div class="cart-item-actions">
                <button class="delete-btn" onclick="removeItem(${item.cartId})">删除</button>
            </div>
        </div>
    `);
}

function updateCheckoutSection(total, hasValidItems) {
    const checkoutSection = $('.cart-summary');
    if (hasValidItems) {
        checkoutSection.show();
        $('#totalAmount').text(total.toFixed(2));
        $('#checkoutBtn').prop('disabled', false);
    } else {
        if ($('.cart-item').length > 0) {
            // 只有无效商品
            checkoutSection.show();
            $('#totalAmount').text('0.00');
            $('#checkoutBtn').prop('disabled', true);
        } else {
            // 购物车完全为空
            checkoutSection.hide();
        }
    }
}

function updateQuantity(cartId, newAmount) {
    if (newAmount < 1) return;
    
    $.ajax({
        url: '/api/cart/update',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({
            cartId: cartId,
            amount: newAmount
        }),
        success: function(response) {
            if (response.code === 200) {
                loadCart();
            } else {
                alert(response.message);
            }
        }
    });
}

function removeItem(cartId) {
    $.ajax({
        url: `/api/cart/delete/${cartId}`,
        type: 'DELETE',
        success: function(response) {
            if (response.code === 200) {
                showMessage('已移除', 'success', 1000);
                loadCart();
            } else {
                showMessage(response.message || '删除失败', 'error', 1000);
            }
        },
        error: function() {
            showMessage('删除失败，请重试', 'error', 1000);
        }
    });
}

function submitOrder() {
    const userId = localStorage.getItem('userId');
    if (!userId) {
        window.location.href = '../index.html';
        return;
    }

    $.ajax({
        url: `/api/cart/valid/${userId}`,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const validItems = response.data;
                if (validItems.length === 0) {
                    showMessage('没有可提交的商品！', 'error');
                    return;
                }

                // 显示订单确认模态框
                const modal = $('#orderConfirmModal');
                const itemsContainer = modal.find('.order-items');
                itemsContainer.empty();
                
                let total = 0;
                validItems.forEach(item => {
                    itemsContainer.append(`
                        <div class="order-item-preview">
                            <div class="item-name-quantity">
                                <div class="item-name">${item.commodityName}</div>
                                <div class="item-quantity">数量：${item.amount}</div>
                            </div>
                            <div class="item-subtotal">¥${item.money.toFixed(2)}</div>
                        </div>
                    `);
                    total += item.money;
                });

                modal.find('.order-total').html(`总计：¥${total.toFixed(2)}`);
                modal.css('display', 'flex');
            } else {
                showMessage(response.message || '获取有效商品失败', 'error');
            }
        },
        error: function() {
            showMessage('获取有效商品失败，请重试', 'error');
        }
    });
}

function createOrder(userId) {
    $.ajax({
        url: '/api/order/create',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            userId: parseInt(userId)
        }),
        success: function(response) {
            if (response.code === 200) {
                showMessage('订单提交成功！', 'success');
                setTimeout(() => {
                    window.location.href = 'orders.html';
                }, 1500);
            } else {
                showMessage(response.message || '提交订单失败', 'error');
            }
        },
        error: function() {
            showMessage('提交订单失败，请重试', 'error');
        }
    });
}

// 添加消息提示函数
function showMessage(message, type = 'success', duration = 2000) {
    const messageDiv = $('<div>')
        .addClass('message')
        .addClass(type)
        .text(message)
        .css('opacity', 0);

    $('body').append(messageDiv);
    messageDiv.animate({ opacity: 1 }, 300);

    setTimeout(() => {
        messageDiv.animate({ opacity: 0 }, 300, function() {
            $(this).remove();
        });
    }, duration);
}

function showEmptyCart(container) {
    container.html(`
        <div class="empty-cart">
            <div class="icon">🛒</div>
            <h3>购物车还是空的</h3>
            <p>去挑选一些心仪的商品吧！</p>
            <a href="index.html" class="shop-now-btn">
                立即购物
            </a>
        </div>
    `);
    $('.cart-summary').hide();
} 